<template>
  <div class="common-form">
    <div class="top-nav">
      <p class="nav-title">专栏管理 > 新建专栏</p>
    </div>
    <common-form :formConfig="formConfig" @input="onFormUpdated"></common-form>
    <div class="form-operation">
      <button class="form-btn btn-primary" :class="{'btn-disable':publishing}"  @click="doSubmit">{{submitBtnName}}</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doPreview">预览</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doCancel">取消</button>
    </div>
  </div>
</template>

<script>
import * as types from '../../../store/mutation-types';
import CommonForm from '../../form/CommonForm.vue';

export default {
  name: 'createInfo',
  components:{
    "common-form":CommonForm
  },
  data() {
    let editingInfoData = this.$store.state.createInfo.editingInfoData;
    return {
      formData: {},
      validate: {},
      specialColumnId:editingInfoData.id,
      previewPopup: null,
      formConfig: [{
        name: 'title',
        title: '专栏标题',
        desc: '专栏的名称，8~24个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'text',
        value: editingInfoData.title,
        extra: {
          placeHolder: '8~24个字符',
          limit: [8, 24, 1]
        }
      }, {
        name: 'simpleDescription',
        title: '一句话简介',
        desc: '简单概括专栏，显示在专兰标题的下方，8~28个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'text',
        value: editingInfoData.simpleDescription,
        extra: {
          placeHolder: '8~28个字符',
          limit: [8, 28, 1]
        }
      }, {
        name: 'specialColumnDescription',
        title: '专栏介绍',
        desc: '详细介绍专栏内容，20~1000个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'textarea',
        value: editingInfoData.specialColumnDescription,
        extra: {
          placeHolder: '20~1000个字符',
          limit: [20, 1000, 1]
        }
      },{
        name: 'audience',
        title: '适宜人群',
        desc: '适合订阅此专栏的用户类型，10~1000个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'textarea',
        value: editingInfoData.audience,
        extra: {
          placeHolder: '10~1000个字符',
          limit: [10, 1000, 1]
        }
      },{
        name: 'instruction',
        title: '订阅须知',
        desc: '更新时间、频率，或者课程包的最少集数等信息，10~1000个字符(一个中文汉字或符号算两个字符)',
        require: true,
        type: 'textarea',
        value: editingInfoData.instruction,
        extra: {
          placeHolder: '10~1000个字符',
          limit: [10, 1000, 1]
        }
      }, {
        name: 'photo',
        title: '专栏作者照片',
        require: true,
        type: 'cover',
        value: editingInfoData.photo,
        extra: {
          fileDesc: '专栏的作者照片。尺寸142*190,大小不超过2M。',
          maxFileSize:2*1024*1024,
          width: 142,
          height: 190,
          viewWidth:130,
          viewHeight:95
        }
      },{
        name: 'backgroundImage',
        title: '专栏背景图',
        require: true,
        type: 'cover',
        value: editingInfoData.backgroundImage,
        extra: {
          fileDesc: '专栏详情页的专栏背景图。尺寸750*320,大小不超过2M。',
          maxFileSize:2*1024*1024,
          width: 750,
          height: 320,
          viewWidth:130,
          viewHeight:95
        }
      }],
      publishing: false,
      submit: false
    };
  },
  computed: {
    hasChange: {
      cache: false,
      get() {
        let changed = 0;
        this.formConfig.forEach((item) => {
          let formItem = this.formData[item.name];
          if (formItem && formItem !== item.value) {
            changed++;
          }
        });
        return changed;
      }
    },
    columnStatus(){
      return this.$store.state.createInfo.status;
    },
    submitBtnName(){
      return this.columnStatus == 2 ? "提交" : "下一步";
    }
  },
  methods: {
    onFormUpdated({formData, validate, byUser}) {
      this.formData = formData;
      this.validate = validate;
    },
    doSubmit() {
      if (!this.publishing) {
        for (let i = 0; i < this.formConfig.length; i++) {
          let config = this.formConfig[i];
          let validate = this.validate[config.name];
          if (!validate.ok) {
            this.$store.dispatch('alert', `${config.title}${validate.info}`);
            return false;
          }
        }
        this.publishing = true;

        this.formData.type = parseInt(this.$route.params.id);//专栏类型 1|期刊专栏, 2|课程专栏
        this.$store.dispatch('updateFormDataInfo', this.formData);//更新FormData

        if(this.columnStatus == 2){//已发布，只能修改信息
          this.formData.id = this.specialColumnId;
          this.$store.dispatch('updateFormDataInfo', this.formData);//更新FormData

          this.$store.dispatch('submitForm').then((res) => {
            this.clearValue();
            this.submit = true;
            this.publishing = false;

            this.$router.push('/columns');//修改专栏直接就提交了
          }, () => {
            this.publishing = false;
          });
        }else if(!this.columnStatus || this.columnStatus == 1){//新建及未发布草稿状态，可以继续修改价格
          this.clearValue();
          this.submit = true;
          this.publishing = false;

          this.$router.push('/columns/create/price/'+this.$route.params.id);//新建跳转到价格设置
        }else{
          this.$store.dispatch('alert', `专栏下线`);
        }
      }
    },
    doPreview() {
      let delay = 0;
      if (this.previewPopup == null || this.previewPopup.closed) {
        let viewWidth = 900;
        let viewHeight = 800;
        let offsetLeft = (window.screen.availWidth - viewWidth)/2;
        let offsetTop = (window.screen.availHeight - 30 - viewHeight)/2;
        let url = C_OPEN + '/mob/static/column/preview.htm?type=88&project=static&id=' + this.specialColumnId;
        this.previewPopup = window.open(url,"",`height=${viewHeight},width=${viewWidth},top=${offsetTop},left=${offsetLeft},status=no,toolbar=no,menubar=no,location=no`);
        delay = 1500;
      }
      setTimeout(() => {
        this.previewPopup.postMessage({
          id: this.specialColumnId,
          title: this.formData.title,
          simpleDescription: this.formData.simpleDescription,
          specialColumnDescription: this.formData.specialColumnDescription,
          audience: this.formData.audience,
          instruction: this.formData.instruction,
          photo: this.formData.photo,
          backgroundImage: this.formData.backgroundImage,
          status: this.columnStatus
        }, C_OPEN);
        this.previewPopup.focus();
      }, delay);
    },
    doCancel() {
      this.$router.push('/columns');//判断在beforeRouteLeave里判断
    },
    clearValue() {
      this.formConfig.forEach((input) => {
        input.value = null;
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.$store.state.user.status !== 1) {
        vm.$router.push('/columns')
      }
    })
  },
  beforeRouteLeave(to, from, next) {
    if (!this.submit && this.hasChange > 0) {
      this.$store.dispatch('confirm', '您已输入的内容将会丢失，是否确定？').then(()=> {
        this.$store.commit(types.CLEAR_EDIT_STATE);
        this.previewPopup && this.previewPopup.close();
        next();
      }, () => {
        next(false);
      });
    } else {
      this.previewPopup && this.previewPopup.close();
      this.$store.commit(types.CLEAR_EDIT_STATE);
      next();
    }
  }
};
</script>

<style lang="less" rel="stylesheet/less">
.common-form{
  .top-nav{
    height: 40px;
    margin-bottom: 30px;
    border-bottom: 1px solid #2e9057;
    .nav-title{
      font-size: 20px;
      color: #2e9057;
    }
  }
}
</style>
